package com.dcrzl.gazgmh.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

public abstract class PageUtils {
    /**
     * 获取分页对象
     *
     * @param baseEntity       分页查询参数
     */
    public  static <T> IPage<T> getPageParam(BaseEntity baseEntity) {
        return getPageParam(baseEntity,null,false);
    }

    /**
     * 获取分页对象
     *
     * @param baseEntity       分页查询参数
     */
    public  static <T> IPage<T> getPageParam(BaseEntity baseEntity, String defaultOrderField, Boolean isAsc) {
        if(baseEntity.getPageSize()==null){
            baseEntity.setPageSize(-1);
            baseEntity.setPageNumber(1);
        }
        //分页对象
        Page<T> page = new Page<>(baseEntity.getPageNumber(), baseEntity.getPageSize());
        //排序字段
        String orderField = String.valueOf(baseEntity.getOrderField());
        String order = String.valueOf(baseEntity.getOrder());

        //前端字段排序
        List<OrderItem> orderItemList = new ArrayList<>();
        if (StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)) {
            if ("asc".equalsIgnoreCase(order)) {
                 orderItemList.add(OrderItem.asc(orderField));
            } else {
                orderItemList.add(OrderItem.desc(orderField));
            }
        }
        //没有排序字段，则不排序
        if (StringUtils.isNotBlank(defaultOrderField)) {
            //默认排序
            if (isAsc) {
                orderItemList.add(OrderItem.asc(defaultOrderField));
            } else {
                orderItemList.add(OrderItem.desc(defaultOrderField));
            }
        }
        page.addOrder(orderItemList);
        return page;
    }

    public static <T> PageInfo<T> startPage(IPage<T> page) {
        PageInfo<T> pageInfo = new PageInfo<>();
        return pageInfo.setList(page.getRecords()).setTotal((int) page.getTotal());
    }





}
